package com.bawei.mdm2207alast.file

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import coil.compose.AsyncImage
import com.bawei.mdm2207alast.R
import com.bawei.mdm2207alast.base.OnError
import com.bawei.mdm2207alast.base.OnLoading
import com.bawei.mdm2207alast.base.OnSuccess
import com.bawei.mdm2207alast.common.BaseTitle
import com.bawei.mdm2207alast.model.DeleteFileEntity
import com.bawei.mdm2207alast.model.FileEntity
import com.bawei.mdm2207alast.route.RouteConfig
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

/**
 * 作者：赵亮
 * 时间：2024/12/16 15:34
 * 功能：线上文件
 */
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun OnLineFilesPage(
    navController: NavController = rememberNavController(),
    viewModel: FileViewModel = hiltViewModel()
) {

    // 1. 数据
    val list = remember {
        SnapshotStateList<FileEntity.Data>()
    }
    // 要从列表中删除的文件
    var deleteId by remember {
        mutableStateOf(-1)
    }
    LaunchedEffect(key1 = "") {
        launch {
            viewModel.uiState.collect {
                when (it) {
                    is OnError -> {
                        ToastUtils.showShort(it.msg.toString())
                    }

                    OnLoading -> {}
                    is OnSuccess<*> -> {
                        try {
                            when (it.data) {
                                is FileEntity -> {
                                    // 查询文件列表成功
                                    list.clear()
                                    list.addAll(it.data.data)
                                }

                                is DeleteFileEntity -> {
                                    // 删除文件成功
                                    ToastUtils.showShort(it.data.msg)
                                    Log.i("TAG", "OnLineFilesPage删除前: ${list.size}$list")
                                    list.removeAt(deleteId)
                                    Log.i("TAG", "OnLineFilesPage删除后: ${list.size}$list")
                                }
                            }
                        }catch (e:Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }
        }
        launch {
            viewModel.sendIntent(FileIntent.SelDoc(mapOf("userId" to 1, "page" to 1)))
        }
    }

    Scaffold(floatingActionButton = {
        Icon(imageVector = Icons.Default.Add, contentDescription = null, modifier = Modifier.clickable {
            navController.navigate(RouteConfig.LOCAL_FILE)
        })
    }) {
        Column {
            BaseTitle(navController = navController, title = "文件")
            // 2. 展示
            if (list.isEmpty()) {
                Box(modifier = Modifier.fillMaxSize()) {
                    Text(text = "暂无内容", modifier = Modifier.align(Alignment.Center))
                }
            } else {
                LazyColumn(
                    modifier = Modifier.padding(start = 10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    items(list) {

                        // 是否显示删除对话框
                        var isShow by remember {
                            mutableStateOf(false)
                        }

                        Row(modifier = Modifier.clickable {
                            isShow = true
                        }) {
                            // 文件图片
                            AsyncImage(
                                placeholder = painterResource(id = R.drawable.icon64),
                                error = painterResource(id = R.drawable.icon3),
                                contentScale = ContentScale.Crop,
                                modifier = Modifier
                                    .size(40.dp)
                                    .clip(RoundedCornerShape(10.dp)),
                                model = it.filePath.replace(
                                    "http://10.161.9.80:8383",
                                    "https://47ee78mh3302.vicp.fun"
                                ), contentDescription = null
                            )
                            Column(modifier = Modifier.padding(start = 10.dp)) {
                                Text(text = it.fileName, fontSize = 12.sp)
                                Spacer(modifier = Modifier.height(10.dp))
                                Text(
                                    text = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(it.fileTime),
                                    fontSize = 12.sp
                                )
                            }
                        }
                        if (isShow) {
                            AlertDialog(
                                onDismissRequest = { isShow = false },
                                title = { Text(text = "删除") },
                                text = { Text(text = "是否删除${it.fileName}吗？") },
                                dismissButton = {
                                    Text(text = "取消", modifier = Modifier.clickable {
                                        isShow = false
                                    })
                                },
                                confirmButton = {
                                    Text(text = "确定", modifier = Modifier.clickable {
                                        isShow = false
                                        // 发送删除文件的意图
                                        deleteId = list.indexOf(it)
                                        viewModel.sendIntent(FileIntent.DelDoc(mapOf("FileId" to it.fileId)))
                                    })
                                })
                        }
                    }
                }
            }

        }
    }
}

@Preview(showSystemUi = true)
@Composable
fun OnLineFilesPagePreview() {
    OnLineFilesPage()
}

